define(
	[
		'require',
		'echarts',
		'echarts/chart/line',
		'zrender/tool/util',
		'apm/ui/business_chart_base'
	],
	function (require) {
		"use strict";

		var echarts = require('echarts');
		var zrUtil = require('zrender/tool/util');

		var forEach = Ember.EnumerableUtils.forEach;

		var baseObject = 
		{
			type: 'bar',
			itemStyle: {

            
				normal: {
					barBorderRadius: 0,
					color: function(params) {
						
						// build a color map as your need.
						var colorList = [
						  '#81f26f','#03afff','#81f26f','#03afff','#81f26f','#03afff','#81f26f','#03afff'
						];
						return colorList[(params.dataIndex)%2];
					},
					label: {
						show: false,
						position: 'top',
						formatter: '{c}'
					}
				},
				emphasis: {
	                barBorderRadius: 0
	            }
			},
			data:[]
		};

		var Component = require("apm/ui/business_chart_base").extend({
			_getDefaultOption: function(){
				var view = this;
				return {
					 title : {
				       
				        textStyle: {
				        	color:"#fff",
				        	fontSize: 12,
				        },
				         x:"center"
				    },
					tooltip: {
						 trigger: 'axis',
						 axisPointer : {            // 坐标轴指示器，坐标轴触发有效
						 	type: 'shadow',
				            shadowStyle: {
						        color: 'rgba(150,150,150,0.3)',
						        width: 'auto',
						        type: 'default'
						    }
				         },
				         formatter: function (value, index) {
							var text = value[0]["name"],
								data = view.get("newDate"),
								dataKey = view.get("dataKey"),
								num = index+1;
							var arr = text.split("");

							var index = parseInt(index.substring(index.indexOf(":")+1));

							// var index = JSON.parse(str);
							for(var i=0;i<arr.length-1;i++){
								if(i%80 == 0 && i !== 0){
									arr.splice(i,0,",<br/>")
								}
							}

					    	var text = arr.join('');

					    	dataKey.forEach(function(node){
								var newObject = view.groupByString(node,{});
								text = text+"<br/>"+newObject["name"]+' : ' + data[index][node];
							});

					        return text;
						 }
					},
					grid: {
						x: 90,
						y: 40,
						x2: 30,
						y2: 30,
						borderWidth: 1,
						borderColor:"#215b92",
						zlevel:5
					},
					xAxis: [
						{	
							zlevel:0,
							type: 'value',
	
							splitLine : {//分割线
								show : true,
								lineStyle: {
									color:"#215b92"
								}
							},
							axisLine : {
								show:false
							},
							axisTick: {
								show: false,
							},
							axisLabel : {
								show : true,
								rotate : 0,
								interval : 0,
								margin : 10,
								textStyle: {
									color: "#6ac5fe"
								},
								formatter: function (value, index) {
								
								    var text = value;
								   
								    if(typeof value == "number"){
								    	return value;
								    }
								    if(text.indexOf("\n") !=-1){
								    	text = text.substring(0,text.indexOf("\n"))+" "+ text.substring(text.indexOf("\n")+1);
								    }
								    if(value.indexOf("@") != -1){
								    	text =  value.substring(0,value.indexOf("@"));
								    	if(text.length > 7){
								    		text = text.substring(0,7)+'...';
								    	}
								    	
								    }else{
								    	var width = window.screen.width;
		
										if(width >1440){
											if(text.length >8){
									    		text = text.substring(0,9)+'...';
									    	}
										}else if(width <=1440){
											if(text.length >6){
									    		text = text.substring(0,6)+'...';
									    	}
										}
								    	
								    }
								    
								    return text;
								}
							}
						}
					],
					yAxis: [
						{	

							type: 'value',
						
							splitLine : {//分割线
								show : true,
								lineStyle: {
									color:"#215b92"
								}
							},
							axisTick: {
								show: false,
							},

							axisLabel : {
								show : true,
								interval : 0,
								rotate : 0,
								margin : 10,
								textStyle: {
									color: "#6ac5fe"
								},
								formatter:function(val){
									if(typeof val == "string"){
										val = val.split(" ").join("\n");
									};
								    return val;
								}
							},
							splitNumber:5
						}
					],
					series: [
						
					]					
				};
			},

			_translateOption: function(option){
				if(this.get("pos") === "left"){
					this._translateYAxis(option);
				}else{
					this._translateXAxis(option);
				}
				
				this._translateSeries(option);
				// this._translateOther(option);
			},

			_translateXAxis: function(option){
				var view = this;
				var data = this.get("newDate")||[];

				var xAxisData = option.xAxis[0].data = [];

				option.xAxis[0].type = "category";
				option.yAxis[0].type = "value";

				forEach(data, function(performance){
					xAxisData.push(view._translateXAxisDataItem(performance));
				});

				if(xAxisData.length == 0){
					xAxisData.push("-");
				}
			},

			_translateYAxis: function(option){
				var view = this;
				var data = this.get("newDate")||[];

				var yAxisData = option.yAxis[0].data = [];

				option.yAxis[0].type = "category";
				option.xAxis[0].type = "value";

				forEach(data, function(performance){
					yAxisData.push(view._translateXAxisDataItem(performance));
				});

				if(yAxisData.length == 0){
					yAxisData.push("-");
				}
			},

			/**
			 * 将原始值转换为柱形图的xAxis配置
			 */
			_translateXAxisDataItem: function(performance){
				var name = this.get("name");
				return performance[name];
			},

			groupByString: function(node,newObject){
				if(node == "appInterruptCount"){
					newObject["name"] = "服务中断次数";
				}else if(node == "appInterruptTime"){
					newObject["name"] = "服务中断时间（分钟）";
				}else if(node == "appAvailableRate"){
					newObject["name"] = "可用率%";
				}else if(node == "50Count"){
					newObject["name"] = "严重";
				}else if(node == "20Count"){
					newObject["name"] = "告警";
				}else if(node == "10Count"){
					newObject["name"] = "提醒";
				}else if(node == "count"){
					newObject["name"] = "交易量";
				}else if(node == "responseTime"){
					newObject["name"] = "平均响应时间";
				}else if(node == "success_rate" ){
					newObject["name"] = "成功率";
				}else if(node == 'system/response_time/avg'){
					newObject["name"] = "系统平均响应时间";
				}else if(node == 'system/success/rate' || node == "business/success/rate"){
					newObject["name"] = "成功率";
				}else if(node == 'system/throughput/total_minute'){
					newObject["name"] = "吞吐量/分钟";
				}else if(node == 'business/throughput/total_minute'){
					newObject["name"] = "交易量/分钟";
				}else if(node == 'system/throughput/total_minute'){
					newObject["name"] = "吞吐量/分钟";
				}else if(node == 'business/response_time/avg'){
					newObject["name"] = "交易平均响应时间";
				}
				return newObject;
			},


			//通过字段给tiptool赋值一个总名称和push数据
			tiptoolName: function(node,newObject){
					var data = this.get("newDate")||[],
						view = this;

					var newObject = view.groupByString(node,newObject);

					forEach(data, function(performance){
						 newObject["data"].push(view._translateSeriesDataItem(performance[node]));
					});
					return newObject;
			},

			//填充Series里的数据（注意Series[0]这样赋值是一个坑，push进入才行）
			_translateSeries: function(option){

				var name = this.get("name");
				
				var view = this;
				
			

				if(view.get("dataKey").length == 1){
					option.series = [];
					option.title.text = view.get("title");

					forEach(Ember.A(view.get("dataKey")),function(node,index){
						var newObject = Ember.copy(baseObject, true);

						

						var newObject = view.tiptoolName(node,newObject);

						//来计算柱体的宽度为60%

						var leftWidth = ((view.$().height()*0.6)/newObject["data"].length)*0.6;
						var bottomWidth = ((view.$().width()*0.79)/newObject["data"].length)*0.6;

						if(view.get("pos") == "left"){
							newObject["barWidth"] = (leftWidth)>=50?50:leftWidth;
						}else{
							newObject["barWidth"] = (bottomWidth)>=50?50:bottomWidth;
						}
						
						option.series.push(newObject);
					});
	
				}else{
					option.series = [];
					option.title.text = view.get("title");



					forEach(Ember.A(view.get("dataKey")),function(node,index){
						var newObject = Ember.copy(baseObject, true);
						newObject["barWidth"] = view.get("barWidth");


					
						var newObject = view.tiptoolName(node,newObject);

						//来计算柱体的宽度为60%

						var leftWidth = ((view.$().height()*0.6)/newObject["data"].length)*0.6/view.get("data").length;
						var bottomWidth = ((view.$().width()*0.79)/newObject["data"].length)*0.6/view.get("dataKey").length;
						
						if(view.get("colorNum")){
							newObject["stack"] = "count";
							if(index == 0){
								newObject["itemStyle"]["normal"]["color"] = "#ff5252";
							}else if(index == 1){
								newObject["itemStyle"]["normal"]["color"] = "#ffeb0b";
							}else if(index == 2){
								newObject["itemStyle"]["normal"]["color"] = "#66dc6b";
							}
						    bottomWidth = ((view.$().width()*0.79)/newObject["data"].length)*0.6/1;
						};

						if(view.get("pos") == "left"){
							newObject["barWidth"] =  (leftWidth)>=50?50:leftWidth;
						}else{
							newObject["barWidth"] = (bottomWidth)>=50?50:bottomWidth;
						}

						option.series.push(newObject);
					});
					
				}
			
			},

			// _translateOther: function(option){
			// 	option.yAxis[0].name = this.get("yName")||"";
			// 	if(this.get("yMax")) {
			// 		option.yAxis[0].max = this.get("yMax");
			// 	}

			// 	if(!this.hasData){
			// 		option.yAxis[0].max = 100;
			// 	}

			// 	if(this.dataKey && this.dataKey == "system/score/apdex"){
			// 		option.yAxis[0].splitNumber = 1;
			// 	}
			// },


			

			_translateSeriesDataItem: function(orgiVal){
				var value = Ember.isNone(orgiVal) ? "-" : orgiVal;

				
				if(value !== "-"){
					this.hasData = true;
				}
			
				return  value;
			},

			// _tooltipFormatter: function(type){
			// 	return function(params, ticket, callback){
			// 		params = Ember.A(params||[]);
			// 		var formatter = APM.util.indicatorFormatter(type);
			// 		var tooltip = params[1] + '：' + formatter(params[2]);
			// 		return tooltip;
			// 	}
			// },

			_resizeChart: function(){
				// this.updateAxisLabelInterval();
				this._super();
			}
		});

		APM.ui.BrowserBar = Component;

		return Component;
	}
);